from datetime import datetime
import json
from flask import request, jsonify, session, g
from sqlalchemy import or_

from app import db, csrf
from . import user_bp
from app.app_1_0.auth.models import User, Role, Permission
from ..auth.auth import login_require
from ..auth import init_permission
from app.app_1_0.user import tasks
# from ..auth.auth import permission_required
from ...common.utils import exception_catch, page_search_order_filter


@user_bp.route('/register', methods=['POST'])
@csrf.exempt
def register():
    params = request.get_json()
    username = params.get('name')
    password = params.get('password')
    password2 = params.pop('password2')
    email = params.get('email')
    if not all([username, password]):
        return jsonify({'code': 4000, 'info': "信息填写不全"})
    if password != password2:
        return jsonify({'code': 4001, 'info': "两次密码不一致"})
    if User.query.filter(or_(User.name == username, User.email == email)).first():
        return jsonify({'code': 4002, 'info': "用户名或邮箱已注册过"})
    user = User(**params)
    # user.register_time = datetime.now()
    db.session.add(user)
    db.session.commit()
    user.roles.append(Role.query.filter(Role.id == 1).first())  # 用户注册被分配默认角色
    return jsonify({'code': 0, 'info': 'OK'})


@user_bp.route('/login', methods=['POST'])
@csrf.exempt
def login():
    if session.get('user_id'):
        return jsonify({'code': 0, 'info': 'had been logined!'})
    # params = json.loads(request.data.decode())
    # print(request)
    params = request.get_json()
    username = params.get('name')
    password = params.get('password')
    print('name:{0} password: {1}'.format(username, password))
    if not all([username, password]):
        return jsonify({'code': 400, 'info': '参数不全'})
    user = User.query.filter_by(name=username).first()
    if not user:
        return jsonify({'code': 400, 'info': '用户不存在'})
    if not user.verify_password(password):
        return jsonify({'code': 400, 'info': '密码错误'})
    # 缓存用户信息session
    session['user_id'] = user.id
    session['name'] = user.name
    session['login_time'] = datetime.now()
    # 用户权限初始化
    # init_permission(request, user)

    return jsonify({'code': 0, 'info': 'login successfully'})


@user_bp.route('/logout', methods=['GET'])
@login_require
def logout():
    g.user_id = None
    session.clear()
    return jsonify({'code': 0, 'info': 'ok', 'error': '', 'result': []})


@user_bp.route("/test", methods=['GET'])
def test_init_perms():
    user = User.query.filter_by(name="大学").first()
    init_permission(user)
    perms = session.get('perms')
    return jsonify({'code': 0, 'data': perms})


@user_bp.route('/mail', methods=['GET'])
def send_mail():
    tasks.send_mail_task.delay()
    return jsonify({'code': 0, "info": "send email successfully"})


@user_bp.route('/list', methods=['GET'])
@exception_catch
def user_list():
    path = request.path
    # users_obj = User.query.all()
    queryset, count = page_search_order_filter(request, User)
    users = [item.to_dict() for item in queryset]
    return jsonify({'code': 0, 'info': count, 'result': users, 'error': ''})


@user_bp.route('/delete')
def delete_user():
    """
    测试超级权限的
    :return:
    """
    id = request.args.get('id')
    user = User.query.filter_by(id=id).first()
    user.delete(synchronize_session=False)
    db.session.commit()
    return jsonify({'code': 0, 'info': '删除%s成功' % user.name})


@user_bp.route('/add', methods=['POST'])
@csrf.exempt
def add_user():
    params = request.get_json()
    # data = request.data.decode()
    # params = json.loads(data)
    name = params.get('name')
    if User.query.filter_by(name=name).first():
        return jsonify({'code': -1, 'info': 'error', 'error': '用户名已存在', 'result': []})

    role_ids = []
    if params.get('role_ids'):
        if isinstance(params.get('role_ids'), (list, tuple)):
            role_ids = params.pop('role_ids')

    user = User(**params)
    db.session.add(user)
    db.session.flush()
    # role_ids = [3, 4]
    if role_ids:
        User.add_roles(user.id, role_ids)
    db.session.commit()

    return jsonify({'code': 0, 'message': 'ok'})


@user_bp.route('/update', methods=['POST'])
def update_user():
    params = request.get_json()
    id_ = params.get('id')
    role_ids = params.get('role_ids', [])
    if not id_:
        return jsonify({'code': -1, 'info': 'error', 'error': '缺乏参数id', 'result': []})

    try:
        User.query.filter_by(id=id_).update(params)
        db.session.flush()
        # 更新用户的角色
        user = User.query.filter_by(id=id_).first()
        user.roles = Role.query.filter(Role.id.in_(role_ids)).all()
        db.session.commit()
    except Exception as e:
        pass
    return jsonify({'code': 0, 'info': 'ok', 'error': '', 'result': []})


@user_bp.route('/role/list', methods=['GET'])
def user_role_list():
    """获取用户角色"""
    path = request.path
    user_id = request.args.get('id', '27')
    user_id = int(user_id)
    roles = User.query.filter(User.id == user_id).first().roles
    result = [item.role_name for item in roles]
    return jsonify({'code': 0, 'info': 'ok', 'error': '', 'result': result})


@user_bp.route('/role/set', methods=['GET'])
# @login_require
def set_user_role():
    """设置用户角色 删除/增加/修改 """
    user_id = request.args.get('id')
    role_ids = request.args.get('role_ids')  # role_ids = [1,2,3]
    try:
        User.add_roles(user_id, role_ids)
    except Exception as e:
        return jsonify({'code': -1, 'info': 'error', 'error': '角色添加出错', 'result': []})
    return jsonify({'code': 0, 'info': 'error', 'error':  '角色添加成功', 'result': []})


@user_bp.route('/perm/list', methods=['GET'])
def user_perm_list():
    """
    用户所拥有的权限
    :return:
    """
    user_id = request.args.get('id')
    roles = User.query.filter_by(id=user_id).first().roles
    perms_set, tmp_set = set(), set()
    for item in roles:
        tmp_set = perms_set.union(item.permissions)

    return jsonify({'code': 0, 'info': 'ok', 'result': [], 'error': ''})


from tasks.send_email import tasks


@user_bp.route('/perm/set', methods=['GET', 'POST'])
def user_perm_set():
    """
    :return:
    """
    recievers = ["2398175179@qq.com"]
    tasks.send_email.delay(recievers)
    return jsonify({'code': 0})

